package org.bootstrap.controller;


import cn.hutool.core.util.StrUtil;
import org.bootstrap.service.Impl.FileServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文件下载器
 */

@Controller
@PropertySource("classpath:application.yml")
public class FileController {
    private final FileServiceImpl fileService;
    @Value("${local-disk.img_common}")
    private String img_com;
    @Value("${local-disk.img-avg}")
    private String img_avg;

    // 构造器注入
    FileController(FileServiceImpl fileService) {
        this.fileService = fileService;
    }

    @GetMapping(value = "image/{id}", produces = {MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE})
    public @ResponseBody byte[] loadImage(@PathVariable String id, HttpServletResponse response) throws IOException {
        byte[] bytes = fileService.loadImage(id, img_avg);
        if (bytes != null) {
            return bytes;
        } else {
            response.sendError(404);
            return null;
        }
    }

    @GetMapping(value = "media/{id}", produces = {MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE})
    public @ResponseBody byte[] loadMedia(@PathVariable String id, HttpServletResponse response) throws IOException {
        if (StrUtil.isEmpty(id)) {
            response.sendError(500);
            return null;
        }
        byte[] bytes = fileService.loadImage(id, img_com);
        if (bytes != null) {
            return bytes;
        } else {
            response.sendError(404);
            return null;
        }
    }

}
